<template>
  <div class="page flex flex-rc pt-50">
    <div style="width: 80%">
      <!-- Logo -->
      <div class="flex flex-center mb-50">
        <img class="logo" src="/logo.png" />
      </div>

      <!-- 注册邀请码 -->
      <div class="box mb-50">
        <div class="flex flex-center mb-10">
          <div class="title title--bg">邀请码</div>
        </div>

        <van-field
          placeholder="请输入上级邀请码"
          :border="false"
          v-model="inviteId"
        ></van-field>
      </div>

      <!-- 注册按钮 -->
      <div class="register-btn">
        <van-button class="btn" type="primary" @click="register">
          <div class="fz-17">注册</div>
        </van-button>
        <div class="shadow"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { showSuccess, showError, showLoading } from 'js/utils'

const router = useRouter()
const route = useRoute()
const { t } = useI18n()

const inviteId = ref(route.query.inviteId || '')
const loading = ref(null)

// 注册
async function register() {
  try {
    loading.value = showLoading()
    await bindParentAddress()
    loading.value?.close()
    router.replace('/')
  } catch (err) {
    loading.value?.close()
  }
}

// 绑定上级地址
function bindParentAddress() {
  return new Promise(async (resolve, reject) => {
    try {
      const parentAddress = inviteId.value || defaultParentAddress
      console.log('绑定上级地址')
      await userContract.context.methods.referParent(parentAddress).send({
        from: fromAddress,
      })
      showSuccess($t('注册成功'))
      console.log(`绑定上级地址成功：${parentAddress}`)
      resolve(parentAddress)
    } catch (err) {
      showError($t('注册失败'))
      console.error('绑定上级地址失败')
      console.error(err)
      reject(err)
    }
  })
}
</script>

<style lang="scss" scoped>
.page {
  background: url('/register_bg.png') no-repeat center / cover;

  .logo {
    width: 200px;
  }

  .box {
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 0 5px 1px rgba($color: white, $alpha: 0.5);

    :deep(.van-field) {
      border-radius: 100px;
      background-color: #484a54;

      input {
        text-align: center;
      }
    }
  }

  .register-btn {
    position: relative;

    .btn {
      position: relative;
      width: 100%;
      height: 45px;
      z-index: 1;
    }

    .shadow {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: #0745bf;
      transform: translateY(4px);
      border-radius: 4px;
    }
  }
}
</style>
